<template>
  <div class="user_tag_detail_wrapper" >
    <a-card>
      <div>
        <a-row type="flex" justify="space-between">
          <a-col>
            <a-button type="link" icon="left" @click="backTagListPage" style="padding-left:0;font-weight: bolder">返回标签列表页</a-button>
          </a-col>
          <a-col style="padding-top: 2px">
            上次计算状态: {{tagDetail.updateStatus}}
            <a-divider type="vertical" />
            {{tagDetail.displayUpdateType}}
            <a-divider type="vertical" />
            {{tagDetail.displayType}}
            <a-divider type="vertical" />
            {{tagDetail.displayDataType}}
            <a-divider type="vertical" />
            {{tagDetail.creatorName}}
          </a-col>
        </a-row>
        <a-row class="user_tag_display_name">
          <h2>{{tagDetail.displayName}}</h2>
        </a-row>
        <a-row>
          <a-col :span="16">
            <p>{{tagDetail.remark}}</p>
          </a-col>
        </a-row>
      </div>
    </a-card>


    <div class="tag_data_wrap">
      <a-card title="标签人数分布">
        <div class="tag_data">
          <a-row class="tag_data_basic">
            <span class="tag_data_basic_total">{{tagDetail.totalUsers}} </span>人,  基准时间{{tagDetail.baseTime}}, <span>计算完成于 {{tagDetail.finishAt}}</span>
          </a-row>
          <a-row>
            <div style="float: right">
              <a-select
                v-model="chartType"
                style="width: 100px"
                :show-arrow="true"
                @change="updateChart"
              >
                <a-select-option v-for="item in chartTypes" :key="item.value" :label="item.label">
                  {{ item.label }}
                </a-select-option>
              </a-select>
              <a-select
                v-model="topX"
                style="width: 100px;padding-left: 5px"
                :show-arrow="true"
                @change="updateChart"
              >
                <a-select-option v-for="item in topXOption" :key="item.value" :label="item.label">
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </div>
          </a-row>
          <a-row>
            <a-spin :spinning="loading.chart">
              <div class="tag_data_chars" id="chart_wrapper"></div>
            </a-spin>
          </a-row>
        </div>
      </a-card>
    </div>
  </div>
</template>

<script>

import {mapActions} from "vuex";

const DATA_TYPE = {
  "0":"字符串",
  "1":"数值",
  "2":"布尔",
};

const UPDATE_TYPE = {
  "0":"自动更新",
  "1":"手动更新",
}

const TAGE_TYPE = {
  "0":"自定义SQL",
  "1":"事件属性配置",
}

export default {
  name: "UserTagDetail",
  computed: {},
  data (){
    return {
      tag:{},
      loading: {
        chart: false
      },
      tagDetail:{},
      chart: null,
      chartType: 'bar',
      chartTypes: [
        {
          label: '柱状图',
          value: 'bar'
        },
        {
          label: '饼图',
          value: 'pie'
        }
      ],
      topX: 5,
      topXOption: [
        {label: '前5项', value: 5},
        {label: '前10项', value: 10},
        {label: '前15项', value: 15},
        {label: '前20项', value: 20},
        {label: '前50项', value: 50},
      ],
      chartData: []
    }
  },
  methods: {
    ...mapActions('userTagManage', ['getTagDetailById']),
    initPageData (){
      const query = this.$route.query
      if (query && query.tagId){
        this.tagId = query.tagId
      }else {
        return
      }
      if (this.chart) {
        this.chart.dispose();
        this.chart = null;
      }
      this.chart = this.$echarts.init(document.getElementById('chart_wrapper'), 'light', {height: 400})
      this.getTagDetail()
    },
    buildChart(){
      if (!this.tagDetail || !this.tagDetail.tagValueStats || this.tagDetail.tagValueStats.length < 1){
        return
      }
      let option = {
        grid:{
          left: '5%',
            right: '5%',
            top: '5%',
            bottom: '5%',
            containLabel: true
        },
        legend: {
          show: false
        },
        dataset: {
          source: this.tagDetail.tagValueStats,
        },
        tooltip: {
          trigger: 'axis',
          formatter:function (params){
            if (params.length > 0){
              let param = params[0]
              return param.data.value + " : " + param.data.users + "人，占比 " + param.data.percent + "%"
            }else {
              return ""
            }
          }
        },
        toolbox: {},
        xAxis: {
          type: 'value',
        },
        yAxis: {
          type: 'category',
          inverse: true,
        },
        series: [
          {
            type: 'bar',
          }
        ],
        color:['rgba(47,76,164,0.86)']
      }
      this.chart.setOption(option);
    },
    getTagDetail(){
      this.loading.chart = true
      this.getTagDetailById({id: this.tagId}).then(res=>{
        const tagDetail = res
        tagDetail.updateStatus = tagDetail.status ? "成功": "失败"
        const dataType = DATA_TYPE[String(tagDetail.dataType)]
        tagDetail.displayDataType = typeof dataType === 'string' ? dataType : ""
        const updateType = UPDATE_TYPE[String(tagDetail.updateType)]
        tagDetail.displayUpdateType = typeof updateType === 'string' ? updateType : ""
        const type = TAGE_TYPE[String(tagDetail.type)]
        tagDetail.displayType = typeof type === 'string' ? type : ""
        tagDetail.tagValueStats.map(item=>{
          item.percent = (item.users / tagDetail.totalUsers * 100)
        })
        this.tagDetail = tagDetail
        this.updateChart()
      }).catch(err=>{
        this.$message.error('获取标签详情数据失败，原因：' + err)
        console.error(err)
      }).finally(()=>{
        this.loading.chart = false
      })
    },
    updateChart(){
      if (!this.tagDetail || !this.tagDetail.tagValueStats || this.tagDetail.tagValueStats.length < 1){
        return
      }
      this.chart.clear()
      const tagValue = this.tagDetail.tagValueStats
      if (this.topX >= tagValue.length){
        this.chartData = tagValue
      }else{
        let data = tagValue.slice(0, this.topX)
        let users = 0
        let percent = 0
        for (let i = this.topX; i<tagValue.length; i++){
          users += tagValue[i].users
          percent += tagValue[i].percent
        }
        data.push({ value: "其他", users:users, percent: percent})
        data.sort(function (a, b){ return b.users - a.users })
        this.chartData = data
      }
      if (this.chartType === 'bar'){
        this.buildBarChart()
      }else if (this.chartType === 'pie'){
        this.buildPieChart()
      }
    },
    buildBarChart(){
      const options = this.getChartOption()
      options.tooltip = {
        trigger: 'axis',
        formatter: function (params) {
          if (params.length > 0) {
            let param = params[0]
            return param.data.value + " : " + param.data.users + "人，占比 " + (param.data.percent).toFixed(2) + "%"
          } else {
            return ""
          }
        }
      }
      options.xAxis = {type: 'value'}
      options.yAxis = {type: 'category', inverse: true,}
      options.series.push({type: 'bar',})
      options.color= ['rgba(47,76,164,0.86)']
      options.dataset.source = this.chartData
      this.chart.setOption(options);
    },
    buildPieChart(){
      const options = this.getChartOption()
      options.series.push({
        type: 'pie',
        encode: {
          x : 'value',
          y : 'users',
        },
        label: {
          show: true,
          formatter: '{@value}'
        },
        tooltip: {
          trigger: 'item',
          formatter: function (param) {
            return param.data.value + " : " + param.data.users + "人，占比 " + (param.data.percent).toFixed(2) + "%"
          }
        }
      })
      options.dataset.source = this.chartData
      this.chart.setOption(options);
    },
    getChartOption(){
      return {
        grid: {
          left: '5%',
          right: '5%',
          top: '5%',
          bottom: '5%',
          containLabel: true
        },
        legend: {
          show: false
        },
        dataset: {
          source: [],
        },
        tooltip: {},
        toolbox: {},
        series: [],
        color: []
      }
    },
    backTagListPage(){
      this.$router.go(-1)
    }
  },
  mounted() {
    this.initPageData()
  }
}
</script>

<style scoped>
.user_tag_detail_wrapper{
  width: 100%;
}

.user_tag_detail_wrapper>>>.ant-card-body{
  padding-top: 10px;
  padding-bottom: 10px;
}

.user_tag_display_name{
  padding-top: 10px;
}

.tag_data_wrap{
  margin-top: 10px;
}
.tag_data_basic_total{
  font-size: 20px;
  font-weight: bolder;
}
</style>
